<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的笔记 - 笔记系统</title>
    <!-- 引入外部资源 -->
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <!-- 用于AJAX请求 -->

    <!-- Tailwind配置（与编辑页保持一致） -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#4F46E5',
                        secondary: '#F5F5F7',
                        neutral: '#1F2937',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .note-card {
                @apply bg-white rounded-lg shadow-sm hover:shadow-md transition-shadow duration-300 overflow-hidden;
            }
            .btn-action {
                @apply px-3 py-1.5 rounded text-sm transition-colors;
            }
        }
    </style>
</head>
<body class="bg-secondary min-h-screen">
<!-- 顶部导航栏 -->
<header class="bg-white shadow-sm sticky top-0 z-10">
    <div class="container mx-auto px-4 py-3 flex justify-between items-center">
        <div class="flex items-center space-x-2">
            <i class="fa fa-book text-primary text-2xl"></i>
            <h1 class="text-xl font-bold text-neutral">我的笔记系统</h1>
        </div>
        <div class="flex items-center space-x-4">
            <button id="addNoteBtn" class="bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary/90 transition-colors shadow-sm">
                <i class="fa fa-plus mr-1"></i>新建笔记
            </button>
            <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary cursor-pointer hover:bg-primary/20 transition-colors">
                <i class="fa fa-user"></i>
            </div>
        </div>
    </div>
</header>

<!-- 主内容区 -->
<main class="container mx-auto px-4 py-8 max-w-5xl">
    <!-- 搜索与筛选栏 -->
    <div class="bg-white rounded-lg shadow-sm p-4 mb-6">
        <div class="grid grid-cols-1 md:grid-cols-12 gap-3 items-center">
            <div class="md:col-span-5 relative">
                <input type="text" id="searchInput" placeholder="搜索笔记标题或内容..." class="w-full pl-10 pr-4 py-2.5 rounded-lg border border-gray-200 focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none transition-all">
                <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
            </div>
            <div class="md:col-span-3">
                <select id="categoryFilter" class="w-full px-3 py-2.5 rounded-lg border border-gray-200 focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none">
                    <option value="">全部分类</option>
                </select>
            </div>
            <div class="md:col-span-2">
                <select id="pageSize" class="w-full px-3 py-2.5 rounded-lg border border-gray-200 focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none">
                    <option value="10">每页 10 条</option>
                    <option value="20" selected>每页 20 条</option>
                    <option value="50">每页 50 条</option>
                </select>
            </div>
            <div class="md:col-span-2">
                <button id="searchBtn" class="w-full bg-primary text-white px-5 py-2.5 rounded-lg hover:bg-primary/90 transition-colors">
                    <i class="fa fa-search mr-1"></i>搜索
                </button>
            </div>
        </div>
    </div>

    <!-- 笔记统计与筛选 -->
    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 gap-3">
        <div class="text-neutral/80">
            <span id="noteCount" class="font-bold text-primary">0</span> 条笔记
            <span class="mx-2 text-gray-300">|</span>
            <a href="#" class="hover:text-primary transition-colors" id="showAll">全部</a>
            <a href="#" class="hover:text-primary transition-colors ml-4" id="showRecent">最近7天</a>
        </div>
        <div class="text-sm text-neutral/60">
            排序: <span class="font-medium text-neutral">最新更新</span>
        </div>
    </div>

    <!-- 笔记列表 -->
    <div id="noteList" class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <!-- 笔记卡片会通过JS动态生成 -->
        <!-- 加载状态 -->
        <div id="loading" class="col-span-full py-16 text-center">
            <i class="fa fa-spinner fa-spin text-primary text-2xl mb-2"></i>
            <p class="text-neutral/70">加载笔记中...</p>
        </div>

        <!-- 空数据状态（默认隐藏） -->
        <div id="emptyState" class="col-span-full py-16 text-center hidden">
            <i class="fa fa-file-text-o text-gray-300 text-5xl mb-4"></i>
            <p class="text-neutral/70 text-lg">暂无笔记</p>
            <p class="text-neutral/50 mt-2">点击"新建笔记"开始记录你的想法吧</p>
        </div>
    </div>
    <!-- 分页控件 -->
    <div class="container mx-auto px-4 mt-6 flex justify-between items-center">
        <div class="text-neutral/60 text-sm">
            当前第 <span id="currentPageText">1</span> 页，共 <span id="totalPagesText">1</span> 页
        </div>
        <div class="flex gap-2">
            <button id="prevPage" class="px-3 py-2 rounded border border-gray-300 text-neutral hover:bg-gray-50">上一页</button>
            <button id="nextPage" class="px-3 py-2 rounded border border-gray-300 text-neutral hover:bg-gray-50">下一页</button>
        </div>
    </div>
</main>

<!-- 页脚 -->
<footer class="bg-white border-t border-gray-200 py-6 mt-12">
    <div class="container mx-auto px-4 text-center text-neutral/60 text-sm">
        <p>© 2023 我的笔记系统 - 用技术记录生活</p>
    </div>
</footer>

<!-- 删除确认弹窗（默认隐藏） -->
<div id="deleteModal" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center hidden">
    <div class="bg-white rounded-xl p-6 max-w-md w-full mx-4">
        <h3 class="text-xl font-bold text-neutral mb-2">确认删除</h3>
        <p class="text-neutral/70 mb-6">你确定要删除这条笔记吗？删除后不可恢复。</p>
        <div class="flex justify-end gap-3">
            <button id="cancelDelete" class="btn-action border border-gray-300 text-neutral hover:bg-gray-50">
                取消
            </button>
            <button id="confirmDelete" class="btn-action bg-red-500 text-white hover:bg-red-600">
                确认删除
            </button>
        </div>
    </div>
</div>

<script>
    // 全局变量：当前登录用户ID（实际项目中从登录状态获取）
    const CURRENT_USER_ID = 1;
    let currentDeleteId = null;
    let currentPage = 1;
    let totalPages = 1;
    let searchKeyword = null;
    let currentCategoryId = null;

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', () => {
        // 加载分类并请求首屏分页数据
        loadCategories();
        loadPage();

        // 绑定按钮事件
        document.getElementById('addNoteBtn').addEventListener('click', () => {
            // 跳转到新建笔记页
            window.location.href = 'note-edit.html';
        });

        document.getElementById('searchBtn').addEventListener('click', () => {
            const keyword = document.getElementById('searchInput').value.trim();
            searchKeyword = keyword || null;
            currentPage = 1;
            loadPage();
        });

        document.getElementById('categoryFilter').addEventListener('change', (e) => {
            const v = e.target.value;
            currentCategoryId = v ? parseInt(v) : null;
            currentPage = 1;
            loadPage();
        });
        document.getElementById('pageSize').addEventListener('change', () => {
            currentPage = 1;
            loadPage();
        });
        document.getElementById('prevPage').addEventListener('click', () => {
            if (currentPage > 1) { currentPage--; loadPage(); }
        });
        document.getElementById('nextPage').addEventListener('click', () => {
            if (currentPage < totalPages) { currentPage++; loadPage(); }
        });

        document.getElementById('showAll').addEventListener('click', (e) => {
            e.preventDefault();
            // 重置筛选与搜索
            document.getElementById('searchInput').value = '';
            document.getElementById('categoryFilter').value = '';
            searchKeyword = null;
            currentCategoryId = null;
            currentPage = 1;
            loadPage();
        });

        document.getElementById('showRecent').addEventListener('click', (e) => {
            e.preventDefault();
            loadRecent7DaysNotes();
        });

        // 取消删除
        document.getElementById('cancelDelete').addEventListener('click', () => {
            document.getElementById('deleteModal').classList.add('hidden');
            currentDeleteId = null;
        });

        // 确认删除
        document.getElementById('confirmDelete').addEventListener('click', () => {
            if (currentDeleteId) {
                deleteNote(currentDeleteId);
            }
        });
    });

    // 加载分页数据（支持分类过滤与搜索）
    function loadPage() {
        showLoading();
        const pageSize = parseInt(document.getElementById('pageSize').value) || 20;
        const params = { userId: CURRENT_USER_ID, page: currentPage, pageSize };
        if (currentCategoryId) params.categoryId = currentCategoryId;
        const url = (searchKeyword && searchKeyword.trim()) ? '/notes/search' : '/notes/page';
        if (url === '/notes/search') params.keyword = searchKeyword || '';
        axios.get(url, { params })
            .then(res => {
                const data = res.data || {};
                const items = Array.isArray(data.items) ? data.items : (Array.isArray(res.data) ? res.data : []);
                const total = typeof data.total === 'number' ? data.total : items.length;
                totalPages = typeof data.totalPages === 'number' ? data.totalPages : Math.max(1, Math.ceil(total / pageSize));
                renderNoteList(items);
                document.getElementById('noteCount').textContent = String(total);
                document.getElementById('currentPageText').textContent = String(currentPage);
                document.getElementById('totalPagesText').textContent = String(totalPages);
            })
            .catch(err => {
                console.error('加载分页数据失败', err);
                renderNoteList([]);
                document.getElementById('noteCount').textContent = '0';
                document.getElementById('currentPageText').textContent = '1';
                document.getElementById('totalPagesText').textContent = '1';
                alert('加载笔记失败');
            });
    }

    // 保留方法签名，改为设置关键词并加载分页
    function searchNotes(keyword) {
        searchKeyword = keyword || null;
        currentPage = 1;
        loadPage();
    }

    // 加载最近7天的笔记
    function loadRecent7DaysNotes() {
        showLoading();
        axios.get('/notes/recent', { params: { userId: CURRENT_USER_ID } })
            .then(res => {
                const notes = Array.isArray(res.data) ? res.data : [];
                renderNoteList(notes);
                document.getElementById('noteCount').textContent = String(notes.length);
                document.getElementById('currentPageText').textContent = '1';
                document.getElementById('totalPagesText').textContent = '1';
            })
            .catch(err => {
                console.error('加载最近笔记失败', err);
                renderNoteList([]);
                alert('加载最近笔记失败');
            });
    }

    // 渲染笔记列表
    function renderNoteList(notes) {
        const noteListEl = document.getElementById('noteList');
        // 清空列表
        noteListEl.innerHTML = '';

        if (notes.length === 0) {
            // 显示空状态
            noteListEl.innerHTML = `
                    <div class="col-span-full py-16 text-center">
                        <i class="fa fa-file-text-o text-gray-300 text-5xl mb-4"></i>
                        <p class="text-neutral/70 text-lg">未找到笔记</p>
                        <p class="text-neutral/50 mt-2">尝试其他搜索关键词或查看全部笔记</p>
                    </div>
                `;
            document.getElementById('noteCount').textContent = '0';
            return;
        }

        // 渲染笔记卡片
        notes.forEach(note => {
            const noteCard = document.createElement('div');
            noteCard.className = 'note-card';
            noteCard.innerHTML = `
                    <div class="p-5">
                        <h3 class="text-lg font-semibold text-neutral hover:text-primary transition-colors mb-2">
                            <a href="note-detail.html?id=${note.id}">${note.title}</a>
                        </h3>
                        <div class="text-sm text-neutral/50 mb-4">
                            <span>创建于: ${note.createTime}</span>
                            <span class="mx-2">•</span>
                            <span>更新于: ${note.updateTime}</span>
                        </div>
                        <div class="flex justify-end gap-2">
                            <a href="note-edit.html?id=${note.id}" class="btn-action text-primary hover:bg-primary/10">
                                <i class="fa fa-pencil mr-1"></i>编辑
                            </a>
                            <button class="btn-action text-red-500 hover:bg-red-50 delete-btn" data-id="${note.id}">
                                <i class="fa fa-trash mr-1"></i>删除
                            </button>
                        </div>
                    </div>
                `;
            noteListEl.appendChild(noteCard);
        });

        // 数量由调用方根据接口 total 统一更新

        // 绑定删除按钮事件
        document.querySelectorAll('.delete-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                currentDeleteId = parseInt(btn.getAttribute('data-id'));
                document.getElementById('deleteModal').classList.remove('hidden');
            });
        });
    }

    // 显示加载状态
    function showLoading() {
        const noteListEl = document.getElementById('noteList');
        noteListEl.innerHTML = `
                <div class="col-span-full py-16 text-center">
                    <i class="fa fa-spinner fa-spin text-primary text-2xl mb-2"></i>
                    <p class="text-neutral/70">加载中...</p>
                </div>
            `;
    }

    // 删除笔记
    function deleteNote(noteId) {
        showLoading();
        const form = new URLSearchParams();
        form.append('id', String(noteId));
        form.append('userId', String(CURRENT_USER_ID));
        axios.post('/notes/delete', form, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }})
            .then(res => {
                document.getElementById('deleteModal').classList.add('hidden');
                loadPage();
                alert('笔记已删除');
                currentDeleteId = null;
            })
            .catch(err => {
                console.error('删除失败', err);
                alert('删除失败');
                document.getElementById('deleteModal').classList.add('hidden');
                currentDeleteId = null;
                loadPage();
            });
    }

    // 加载分类下拉
    function loadCategories() {
        axios.get('/categories', { params: { userId: CURRENT_USER_ID } })
            .then(res => {
                const sel = document.getElementById('categoryFilter');
                (Array.isArray(res.data) ? res.data : []).forEach(c => {
                    const opt = document.createElement('option');
                    opt.value = c.id;
                    opt.textContent = c.name;
                    sel.appendChild(opt);
                });
            })
            .catch(err => console.warn('加载分类失败', err));
    }
</script>
</body>
</html>